package com.jumi.microservice.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.jumi.microservice.config.UnionPayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author Dirk
 * @Date 2020-08-27 10:20
 */
@Component
public class UnionPayPostTemplate {

    private static final Logger log = LoggerFactory.getLogger(UnionPayPostTemplate.class);

    @Resource
    private UnionPayConfig unionPayConfig;

    public JSONObject post(String url, MultiValueMap<String, Object> parameters) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, List<Object>> entry : parameters.entrySet()) {
            sb.append(entry.getValue().get(0));
        }
        String macStr = Sm3Util.sm3(sb.toString(), unionPayConfig.getKey());
        parameters.add("mac", macStr);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        headers.add("Charset", "UTF-8");
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(parameters, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
        log.info("App支付下单返回：[{}]", responseEntity.getBody());
        JSONObject jsonObject = JSON.parseObject(responseEntity.getBody(), Feature.OrderedField);
        String retMac = jsonObject.getString("mac");
        jsonObject.remove("mac");
        if (!"".equals(retMac)) {
            String localMac = Sm3Util.sm3(jsonObject.toString(), unionPayConfig.getKey());
            log.info(retMac.equals(localMac) ? "验签通过" : "验签失败");
        }
        return jsonObject;
    }
}
